//
//  FirstViewController.m
//  MUPay
//
//  Created by 胡发冬 on 16/5/20.
//  Copyright © 2016年 胡发冬. All rights reserved.
//

#import "FirstViewController.h"

#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>

#import "WXApiRequestHandler.h"
#import "WXApi.h"
#import "payRequsestHandler.h"


#import "ICShowView.h"
#import "WebRequest.h"



#define ScreenSize [UIScreen mainScreen].bounds.size


@interface FirstViewController ()<UITextFieldDelegate>

@end

@implementation FirstViewController
{
    NSString *PayResult;
    NSArray *dataArray;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    PayResult = @"支付结果";
    
    _textFieldOutNo.text = @"";
    _LabelOutStatic.text=@"";
    
    srand( (unsigned)time(0) );
    _textFieldNoncestr.text = [NSString stringWithFormat:@"%d", rand()];
    
    _textFieldNoncestr.keyboardType = UIKeyboardTypeNumberPad;
    _textFieldOutNo.keyboardType = UIKeyboardTypeNumberPad;
    
    _textFieldQueryOutNo.delegate=self;
    //_textFieldNoncestr.delegate=self;
    
    _textFieldQueryOutNo.keyboardType =UIKeyboardTypeNumberPad;
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    NSNotificationCenter *PayNotify = [NSNotificationCenter defaultCenter];
    [PayNotify addObserver:self selector:@selector(PayResult:) name:@"SendNotification" object:nil];
    
}

- (void)PayResult:(NSNotification *)notify{
    //NSLog(@"recv bcast %d", index);
    
    NSDictionary *dict = [notify userInfo];
    NSString *result = [dict objectForKey:@"PayResult"];
    if ([result isEqualToString:@"支付成功"]) {
        PayResult = @"成功!";
    }else{
        PayResult = @"失败!";
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付结果" message:PayResult delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    
}

- (IBAction)aliPay:(UIButton *)sender {
    if (![_textFieldOutNo.text isEqualToString:@""]) {
        
        
        //partner和seller获取失败,提示
        if ([ALI_PARTNER_ID length] == 0 ||
            [SELLER_ID length] == 0 ||
            [PRIVATE_KEY length] == 0)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"缺少partner或者seller或者私钥。"
                                                           delegate:self
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
            [alert show];
            return;
        }

        /*
         *生成订单信息及签名
         */
        //将商品信息赋予AlixPayOrder的成员变量
        Order *order = [[Order alloc] init];
        order.partner = ALI_PARTNER_ID;
        order.sellerID = SELLER_ID;
        order.outTradeNO = _textFieldOutNo.text; //订单ID（由商家自行制定）
        order.subject = @"测试支付"; //商品标题
        order.body = @"测试支付"; //商品描述
        order.totalFee = @"0.01"; //商品价格
        order.notifyURL =  @"http://www.xxx.com"; //回调URL
        
        order.service = @"mobile.securitypay.pay";
        order.paymentType = @"1";
        order.inputCharset = @"utf-8";
        order.itBPay = @"30m";
        order.showURL = @"m.alipay.com";
        
        //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
        NSString *appScheme = @"mupay";
        
        //将商品信息拼接成字符串
        NSString *orderSpec = [order description];
        //NSLog(@"orderSpec = %@",orderSpec);
        
        //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
        id<DataSigner> signer = CreateRSADataSigner(PRIVATE_KEY);
        NSString *signedString = [signer signString:orderSpec];
        
        //将签名成功字符串格式化为订单字符串,请严格按照该格式
        NSString *orderString = nil;
        if (signedString != nil) {
            orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                           orderSpec, signedString, @"RSA"];
            [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                NSLog(@"WEB:reslut = %@",resultDic);
                NSString *notify=@"";
                if ([[NSString stringWithFormat:@"%@",resultDic] rangeOfString:@"resultStatus = 9000"].location != NSNotFound) {
                    notify=@"支付成功";
                }else{
                    notify=@"支付失败";
                }
                NSNotificationCenter *PayNotify = [NSNotificationCenter defaultCenter];
                NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:notify,@"PayResult",nil];
                [PayNotify postNotificationName:@"SendNotification" object:self userInfo:dict];
            }];
        }
    }
}

- (IBAction)WeChatPay:(UIButton *)sender {
    if (![_textFieldOutNo.text isEqualToString:@""]) {

        if ([WXApi isWXAppInstalled]) {
            
            
            
            payRequsestHandler *pay1 = [[payRequsestHandler alloc]init:@"测试支付"  Total_fee:@"1" Order_no:_textFieldOutNo.text];
            NSString *nonce_str = [pay1 getNoncestr];
            NSString *prepay_id = [pay1 getPrepayID];
            
            while (prepay_id == nil) {
            }
            // 设置时间格式
            NSDate *now = [NSDate date];
            NSTimeInterval timeInterval = [now timeIntervalSince1970];
            timeInterval = (int)timeInterval;
            NSString *timestamp = [NSString stringWithFormat:@"%.0lf",timeInterval];
            
            
            
            //调起微信支付···
            PayReq* req             = [[PayReq alloc] init];
            req.partnerId           = MCH_ID;
            req.prepayId            = prepay_id;
            req.nonceStr            = nonce_str;
            req.timeStamp           = timeInterval;
            req.package             = @"Sign=WXpay";
            
            NSMutableDictionary *signParams = [NSMutableDictionary dictionary];
            [signParams setObject: WX_APP_ID forKey:@"appid"];
            [signParams setObject: nonce_str forKey:@"noncestr"];
            [signParams setObject: @"Sign=WXpay" forKey:@"package"];
            [signParams setObject: MCH_ID forKey:@"partnerid"];
            [signParams setObject: timestamp forKey:@"timestamp"];
            [signParams setObject: prepay_id forKey:@"prepayid"];
            
            //生成签名
            req.sign=[pay1 createMd5Sign:signParams];
            [WXApi sendReq:req];
            
            
        }else{
            UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"提示:" message:@"未检测到设备上的微信客户端" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
            [promptAlert show];
        }
    }
}


- (IBAction)createNonceStr:(UIButton *)sender {
    
    
    srand( (unsigned)time(0) );
    NSString *noncestr  = [NSString stringWithFormat:@"%d", rand()];
   
    _textFieldNoncestr.text = noncestr;


}


- (IBAction)createOutNo:(UIButton *)sender {
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [ICShowView showHUDAddedTo:self.view withText:@"加载中..."];
        
    });
    
    
    
    NSString *str = [NSString stringWithFormat:@"&lt;data&gt;&lt;MerBillNo&gt;%@&lt;/MerBillNo&gt;&lt;MerNo&gt;E000002201&lt;/MerNo&gt;&lt;OrderDate&gt;2016-04-13&lt;/OrderDate&gt;&lt;OrderAmount&gt;0.01&lt;/OrderAmount&gt;&lt;OrderSource&gt;03&lt;/OrderSource&gt;&lt;ProductCode&gt;&lt;/ProductCode&gt;&lt;ProductName&gt;挂号&lt;/ProductName&gt;&lt;CreateBy&gt;(null)&lt;/CreateBy&gt;&lt;OrderType&gt;01&lt;/OrderType&gt;&lt;PayType&gt;04&lt;/PayType&gt;&lt;Ord_Source_Ip&gt;&lt;/Ord_Source_Ip&gt;&lt;Ord_Termno&gt;&lt;/Ord_Termno&gt;&lt;Source_Id&gt;(null)&lt;/Source_Id&gt;&lt;Bill_Code&gt;&lt;/Bill_Code&gt;&lt;OrderState&gt;01&lt;/OrderState&gt;&lt;Sign_Type&gt;&lt;/Sign_Type&gt;&lt;SignData&gt;&lt;/SignData&gt;&lt;OrderData&gt;&lt;row&gt;&lt;Card_No&gt;&lt;/Card_No&gt;&lt;Dept_Code&gt;1010300&lt;/Dept_Code&gt;&lt;Dept_Name&gt;神经内科门诊&lt;/Dept_Name&gt;&lt;Exc_Dept_Code&gt;&lt;/Exc_Dept_Code&gt;&lt;Exc_Dept_Name&gt;&lt;/Exc_Dept_Name&gt;&lt;Reg_Type_Code&gt;01&lt;/Reg_Type_Code&gt;&lt;Reg_Type_Name&gt;-&lt;/Reg_Type_Name&gt;&lt;Reg_Level_Code&gt;01&lt;/Reg_Level_Code&gt;&lt;Reg_Level_Name&gt;普通&lt;/Reg_Level_Name&gt;&lt;Doct_Code&gt;&lt;/Doct_Code&gt;&lt;Doct_Name&gt;&lt;/Doct_Name&gt;&lt;Reg_Fee&gt;5.00&lt;/Reg_Fee&gt;&lt;Chk_Fee&gt;0&lt;/Chk_Fee&gt;&lt;Dig_Fee&gt;0.00&lt;/Dig_Fee&gt;&lt;Tot_Amount&gt;5.00&lt;/Tot_Amount&gt;&lt;Noon&gt;下午&lt;/Noon&gt;&lt;See_Date&gt;2016-04-13&lt;/See_Date&gt;&lt;See_Number&gt;24&lt;/See_Number&gt;&lt;/row&gt;&lt;/OrderData&gt;&lt;/data&gt;",_textFieldNoncestr.text];
    WebRequest *soaprequest=[[WebRequest alloc] init];
    soaprequest.PostUrl=@"http://112.74.208.233:6101/MessageApi.asmx";
    dataArray = [[NSMutableArray alloc]init];
    
    [soaprequest postSyncForSession:str AndFuncode:@"F000104" Success:^(NSDictionary *  response) {
        
        NSDictionary *dic = response[@"data"];
        dataArray = dic[@"item"];
        
        //NSLog(@"%@\n %@",dataArray,dic);
        
        
        NSString *labelOrderNo = [NSString stringWithFormat:@"%@",dic[@"OrderNo"]];
        
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
            [ICShowView showMBAlertViewWithMessage:dic[@"RspMsg"]];
            
            //====================================================
            if (![labelOrderNo isEqualToString:@"0"]) {
                if (![labelOrderNo isEqualToString:@"(null)"]) {
                    if (![labelOrderNo isEqualToString:@"<null>"]) {
                        
                        _textFieldOutNo.text = labelOrderNo;
                        
                        _textFieldQueryOutNo.text = _textFieldOutNo.text;
                    }
                }
            }
            
            
        });
        
        
    } falure:^(NSError *response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
        });
        
        
    }];

    
    //NSLog(@"%@",_LabelOutNo.text);
    
    
    
}


- (IBAction)BtnQueryOutStatic:(UIButton *)sender {
    
    //_LabelOutStatic.text=@"已支付";
    
}




//==============产生随机订单号==============
- (NSString *)getTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}


- (IBAction)backBtn:(UIBarButtonItem *)sender {
    
    [self dismissViewControllerAnimated: YES completion: nil ];
    
}


- (IBAction)QueryOutTextFiledChanged:(UITextField *)sender {
    
    //滑动效果（动画）
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动，以使下面腾出地方用于软键盘的显示
    self.view.frame = CGRectMake(0.0f, -216.0f, self.view.frame.size.width, self.view.frame.size.height);//64-216
    
    [UIView commitAnimations];

    _LabelOutStatic.text=@"";
    
    
}




- (IBAction)BtnBackground:(UIButton *)sender {
    
    for (UIView *view in self.view.subviews) {
        [view resignFirstResponder];
    }
    
}
//#pragma mark - 屏幕上弹
//-(void)textFieldDidBeginEditing:(UITextField *)textField
//{
//    //键盘高度216
//    
//    //滑动效果（动画）
//    NSTimeInterval animationDuration = 0.30f;
//    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
//    [UIView setAnimationDuration:animationDuration];
//    
//    //将视图的Y坐标向上移动，以使下面腾出地方用于软键盘的显示
//    self.view.frame = CGRectMake(0.0f, -100.0f, self.view.frame.size.width, self.view.frame.size.height);//64-216
//    
//    [UIView commitAnimations];
//}


#pragma mark -屏幕恢复
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    //滑动效果
    NSTimeInterval animationDuration = 0.3f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //恢复屏幕
    self.view.frame = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);//64-216
    
    [UIView commitAnimations];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
